package com.ikai.ruderesponser;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Servlet that allows users to "Use" a rudeness, creating a new "Use" Entity
 * 
 * @author Ikai Lan <ikai@google.com>
 * 
 */
@SuppressWarnings("serial")
public class UseRudenessServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
	    throws IOException {
	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	if (user != null) {
	    DatastoreService datastore = DatastoreServiceFactory
		    .getDatastoreService();
	    String key = req.getParameter("key");
	    try {
		Key rudenessKey = KeyFactory.stringToKey(key);
		Entity rudeness = datastore.get(rudenessKey);

		Entity use = new Entity("Use");
		use.setProperty("userId", user.getUserId());
		use.setProperty("rudeness", rudenessKey);
		use.setProperty("rudenessBody", rudeness.getProperty("body"));
		use.setProperty("timestamp", new Date());
		datastore.put(use);

		Long updatedCount = (Long) rudeness.getProperty("useCount") + 1;
		rudeness.setProperty("useCount", updatedCount);
		datastore.put(rudeness);

	    } catch (EntityNotFoundException e) {
		resp.sendError(404);
	    }
	    resp.sendRedirect("/");
	} else {
	    resp.sendRedirect(userService.createLoginURL("/"));
	}
    }
}
